// pages/user_info/user_info.js
const mybehavior = require("../../behaviors/requests")
const test = ["123"]
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  behaviors: [mybehavior],
  /**
   * 页面的初始数据
   */
  data: {
    _id: "",
    company: "",
    ID_number: wx.getStorageSync('ID_number'),
    baseUrl: "https://logisticsengineering.gree.com/package_integrated_api",
    baseUrl1: "https://logisticsengineering.gree.com",
    manager: "",
    phone_num: wx.getStorageSync('phone_num'),
    role: "",
    data_auth: "",
    self_info_show2: false,
    self_info: {},
    yam_btn_disabled: false,
    yam_btn: "primary",
    yam_word: "发送",
    count: 0,
    new_ver_code: "",
    new_phonenum: "",
    new_name: "",
    new_ID_number: "",
    name: wx.getStorageSync('name'),
    daiban_num: 10,
    user_info: wx.getStorageSync('name'),
    sqd_total: 0,
    total1: 0,
    total: 0,
    task_count: 0,
    task_count1: 0,
    now_time: "",
    self_info_show3: false,
    ID_number_show: "****",
    msg_show: false,
    we_show: false,
    we_style: "height: 424rpx;",
    yzm_show: false,
    captcha: "",
    imageSrc: "",

  },
  tOWEDataShow() {
    wx.navigateToMiniProgram({
      shortLink: '#小程序://We分析/HlqJ77s2laBDw2y',
      //develop开发版；trial体验版；release正式版
      envVersion: 'release',
      success(res) {
        // 打开成功
        console.log("跳转小程序成功！", res);
      }

    })

  },
  freshUserData() {
    this.setData({
      ID_number: wx.getStorageSync('ID_number'),
      name: wx.getStorageSync('name'),
      user_info: wx.getStorageSync('name'),
      phone_num: wx.getStorageSync('phone_num'),

    })
  },

  // 后台转换用户OPENID 
  getCode() {
    wx.showModal({
      title: '是否确认订阅本系统消息通知？',
      content: '',
      complete: (res) => {
        if (res.cancel) {

        }

        if (res.confirm) {
          wx.login({
            success(res) {
              console.log("xxxx", res);
              if (res.code) {
                // 发起网络请求
                wx.request({
                  url: 'https://logisticsengineering.gree.com/gm_user/get_openid_personal',
                  data: {
                    js_code: res.code,
                    _id: wx.getStorageSync('_id')
                  },

                })
                wx.showModal({
                  title: '订阅成功',
                  showCancel: false,
                  complete: (res) => {

                    if (res.confirm) {
                      wx.requestSubscribeMessage({
                        tmplIds: ['Qq4EMCt24ZVzeR74sHCcdCgZyo7pus8Bf9knNoUHPpM'],
                      })
                    }
                  }
                })
                console.log(res.code)
              } else {
                console.log('登录失败！' + res.errMsg)
              }
            }
          })
        }
      }
    })



  },

  
  getMSG() {  // 拉起授权弹窗
    wx.requestSubscribeMessage({
      tmplIds: ['Qq4EMCt24ZVzeR74sHCcdCgZyo7pus8Bf9knNoUHPpM'],
    })
  },


  onConfirm3() {
    this.setData({
      self_info_show3: false,

    })
  },
  //   申请用户权限
  applyUserDath() {
    wx.requestSubscribeMessage({
      tmplIds: ['Qq4EMCt24ZVzeR74sHCcdCgZyo7pus8Bf9knNoUHPpM'],

    })
    wx.navigateTo({
      url: '/packageB/pages/package/topic_manage/auth_manage/auth_manage',
    })
  },
  // 显示权限
  showDataAuth() {
    this.setData({
      self_info_show3: true,

    })

  },


  routeJump1(e) {
    wx.requestSubscribeMessage({
      tmplIds: ['Qq4EMCt24ZVzeR74sHCcdCgZyo7pus8Bf9knNoUHPpM'],

    })
    console.log(e.currentTarget.dataset.row_data);
    let key = e.currentTarget.dataset.row_data
    wx.navigateTo({
      url: '/packageB/pages/package/task_manager/task_manager?key=' + key,
    })
  },
  // 发送按钮倒计时
  sentBtn() {
    var a = this.data.count
    var t = this.data.yam_word
    if (a < 60) {
      this.setData({
        yam_word: t - 1,
        count: a + 1,
      })
      setTimeout(() => {
        this.sentBtn()
      }, 1000)
    } else {
      this.setData({
        yam_word: "发送验证码",
        yam_btn_disabled: false
      })

    }

  },
  // 发送验证码
  sentCode() {
    let self = this
    if (self.data.new_phonenum == "") {
      wx.showToast({
        title: "不能为空",
        icon: "error"
      })
    } else {
     
    var url = "https://logisticsengineering.gree.com/gm_user/gm_get_verification_code2";
    var data = {
      captcha: self.data.captcha,
      phone_num: self.data.new_phonenum,
    }
      var token = wx.getStorageSync('token')
      console.log("发送验证码", data)
      wx.request({
        url,
        data,
        header: {
          "Authorization": token
        },
        dataType: "json",
        method: "POST",
        success(res) {
          const result = res.data
          if (result.code == 20000) {
            self.setData({
              yzm_show: false,
              captcha: "",
              yam_btn_disabled: true,
              yam_word: 60,
              count: 0,
            })
            self.sentBtn()
            wx.showToast({
              title: result.msg,
              icon: "success"
            });
          } else {
            // self.setData({
            //   phone_num: "",
            // })
            wx.showToast({
              title: result.msg,
              icon: "none"
            })
          }

        },
        fail(res) {
          console.log(res);

        }
      });
    }


  },


  // 获取图形验证码
  BerforeSentCode() {
    if (this.data.checked == false) {
      wx.showToast({
        title: '请阅读并勾选同意《隐私协议》',
        icon: 'none'
      })

    } else {

      wx.showLoading({
        title: '加载中....',
      })
      var url = "https://logisticsengineering.gree.com/gm_user/gm_get_captcha";
      var data = {
        phone_num: this.data.new_phonenum,
      }
      let self = this

      wx.request({
        url: url,
        data: data,
        responseType: 'arraybuffer',
        success(res) {
          if (res.statusCode == 200) {
            const arrayBuffer = res.data;
            // 将 ArrayBuffer 转为 Base64
            const base64 = wx.arrayBufferToBase64(arrayBuffer);
            // 直接用作图片源（需后台返回完整Base64带前缀）
            self.setData({
              imageSrc: 'data:image/png;base64,' + base64,
              yzm_show: true,
            });

          } else {
            wx.showToast({
              title: '手机号有误，请重新确认！',
              icon: 'none'
            })
          }

          wx.hideLoading()

        }
      });

    }

  },

  onCloseLogin() {
    this.setData({
      yzm_show: false,
      captcha: ""
    })
  },
  onConfirmLogin() {
    if (this.data.captcha == "") {
      wx.showToast({
        title: '请输入图形验证码！',
        icon: 'none'
      })
    } else {

      this.sentCode()
    }
  },
  // 修改账户信息
  updateSelfInfo() {
    let self = this
    var url = this.data.baseUrl1 + "/gm_user/wx_update_my_self";
    var data = {
      phone_num: this.data.new_phonenum,
      verification_code: this.data.new_ver_code,
      ID_number: this.data.new_ID_number,
      name: this.data.new_name,
    }
    console.log("修改用户信息", data);
    var token = wx.getStorageSync('token')
    wx.request({
      url,
      data,
      header: {
        "Authorization": token
      },
      dataType: "json",
      method: "POST",
      success(res) {

        const result = res.data
        if (res.code = 20000) {
          wx.setStorageSync('ID_number', self.data.new_ID_number)

          self.setData({
            self_info_show2: false,
            new_ver_code: "",
            ID_number: self.data.new_ID_number
          })
          wx.showToast({
            title: result.msg,
            icon: "success"
          });
          console.log(result.data);
        } else {
          wx.showToast({
            title: result.msg,
            icon: "error"
          });
        }

      },
      fail(res) {
        console.log(res);
        wx.showToast({
          title: result.msg,
          icon: "error"
        });
      }
    });
  },
  showSelfInfo() {
    this.setData({
      self_info_show: true
    })
  },
  showSelfInfo2() {
    this.setData({
      self_info_show2: true
    })
  },
  // 获取待办任务数据
  getDatas() {

    let url = this.data.baseUrl1 + "/pfep2_api/personal_task_manage/query_current_total_task";
    let data = {
      page: 1,
      page_size: 1,
      query_cond: {

      },
      database: ""
    }
    this.post(url, data).then(res => {
      // console.log("获取待办任务数据", res)


      if (res.code == 20000) {
        this.setData({
          task_count: res.data.total,
        })

      } else {
        this.setData({
          task_count: 0,
        })

      }
    }).catch(err => {
      this.setData({
        task_count: 0,
      })

    })



  },
  // 获取经任务数据
  getDatas1() {

    let url = this.data.baseUrl1 + "/pfep2_api/personal_task_manage/query_involved_total_task";
    let data = {
      page: 1,
      page_size: 1,
      query_cond: {

      },
      database: ""
    }
    this.post(url, data).then(res => {
      // console.log("获取待办任务数据", res)


      if (res.code == 20000) {
        this.setData({
          task_count1: res.data.total,
        })

      } else {
        this.setData({
          task_count1: 0,
        })

      }
    }).catch(err => {
      this.setData({
        task_count1: 0,
      })

    })



  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getDatas()
    this.getDatas1()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.freshUserData()

    let room = wx.getStorageSync('room')
    let name = wx.getStorageSync('name')
    if (room == "物流工程室" && name == "甘海森" || room == "物流工程室" && name == "刘文乐" ||room == "物流工程室" && name == "郑楚鑫") {
      this.setData({
        we_show: true,
        we_style: "height: 524rpx;"

      })
    }
    // this.getSelfData()
    const now_time = this.formatDate(new Date())
    // console.log("xxx", now_time);

    // setTimeout(() => {
    this.setData({
      // total: this.data.total1 + this.data.sqd_total,
      room: wx.getStorageSync('room'),
      now_time: now_time

    })
    //   //   console.log("11", this.data.total);
    // }, 1500)

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})